// pages/product-details/product-details.js
import mode from '../../utils/mode'
const wxParse = require('../../wxParse/wxParse.js')
Page({

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        this.setData({
          isShare:1,
        })
        return {
            title:this.data.shareText,
            // dec: this.data.goodInfo.goods_name,
            path: '/pages/product-details/product-details?goodId=' + this.data.goodId + '&shareId=' + this.data.userMessage.id,
            imageUrl: 'https://2am-project.cn/img/20220524/shareCard.png',   //分享图片
        }
    },
    /**
     * 页面的初始数据
     */
    data: {
        temIds:['Wzq0Q8OpleP_KgHNxStTKJ6-8NdvRvqgJnioZ01w7bg','IKdsAyES45qURTGEQMaHqLRq-fpoaU83kNRtz3TcC78'],
        isShare:0,  //是否进行分享
        showShare:false,  //分享成功展示
        shareText:'邀您开启精准护肤之旅',  //分享内容
        price_type: '',      //优惠价类型
        user_price: '0.00',   //预计到手单价
        userMessage: {},   //用户信息
        goodNum: 1,   //购买数量
        goodInfo: {},
        indicatorDots: true,
        vertical: false,
        autoplay: false,
        interval: 2000,
        duration: 500,
        show: false,
        addCartShow: false,
        goodId: '',
        shareId: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let info = wx.getStorageSync('uinfo')
        if (info.user) {
            this.setData({
                shareId: options.shareId,
                userMessage: info.user
            })
        }
        if (options.shareId) {
            if (!info.user||!info.user.id) {
                wx.setStorageSync('shareGood', options.shareId)
                wx.navigateTo({
                    url: '/pages/register/register',
                })
            }
        }
        if (options.goodId) {
            this.setData({
                goodId: options.goodId
            })
            this.getGoodInfo()
        }
    },
    async getGoodInfo () {
        wx.showLoading()
        var that = this
        let data = {}
        if(this.data.userMessage.id)  data.user_id=this.data.userMessage.id
        if(this.data.shareId)  data.share_id=this.data.shareId
        data.goods_id= this.data.goodId||''
        await wx.$api.goodsGetInfo(data).then(res=>{
                if (that.data.shareId) {
                    wx.setStorageSync('shareGood', '')
                }
                if (res.code == 1 && res.data) {
                    let info = res.data
                    let navtitle = (info.goods_name||'') + (info.spec_name||'')
                    wx.setNavigationBarTitle({
                      title: navtitle||'商品详情',
                    })
                    if (!info.goods_carousel || info.goods_carousel.length < 1) {
                        info.goods_carousel = []
                        info.goods_carousel.push(info.goods_thumb)
                    } else if (typeof info.goods_carousel == 'string') {
                        let imgItem = info.goods_carousel
                        info.goods_carousel = []
                        info.goods_carousel.push(imgItem)
                    }else if (info.goods_content) {
                        info.goodContent = wxParse.wxParse('article', 'html', info.goods_content, that, 5)
                    }
                    if(info.estimate_price===''||info.estimate_price===null){
                        info.is_estimate=0
                    }else{
                        info.is_estimate=1
                    }
                    let uInfo = that.data.userMessage
                    let uPrice = info.retail_price
                    let uType = ''
                    if (uInfo && uInfo.consumption_discount > 0) {
                        uPrice = uPrice * uInfo.consumption_discount / 10 * 1
                        uPrice = uPrice.toFixed(2)
                        if (uInfo.grade == 1) {
                            uType = '银钻会员价'
                        } else if (uInfo.grade == 2) {
                            uType = '金钻会员价'
                        } else if (uInfo.grade == 3) {
                            uType = '黑钻会员价'
                        }
                    }
                    let shownum = info.goods_can_sell_number>0?1:0
                    that.setData({
                        price_type: uType,
                        user_price: uPrice,
                        goodInfo: info,
                        goodNum:shownum
                    })
                } else {

                    wx.hideLoading()
                    wx.showToast({
                        title: "商品信息异常",
                        icon: "error"
                    })
                }
                wx.hideLoading()
        })
    },
    goRegister () {
        wx.navigateTo({
            url: '/pages/register/register',
        })
    },
    onChange (e) {   //修改商品数量
        this.setData({
            goodNum: e.detail
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let info = wx.getStorageSync('uinfo')
        let shareId = wx.getStorageSync('shareGood')
        if (info.user) {
            let n = info.user.user_nickname || ''
            let title =  n + '邀您开启精准护肤之旅'
            this.setData({
                shareText: title,
                shareId: shareId,
                userMessage: info.user
            })
        }
        // if(this.data.isShare>0){
        //     this.setData({
        //         showShare:true
        //     })
        // }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    setInfo(){// 订阅消息
        let that = this
        this.setData({
          showShare:false,
          isShare:0
        })
        let shareData={
          user_id:that.data.userMessage.id,
          type:3,
          other_type:'',
        }
        wx.requestSubscribeMessage({
            tmplIds: that.data.temIds,
            success (res) {
              let arr = []
                if(res[that.data.temIds[0]]=='accept'){//拒绝
                  arr.push('1')
                }
                if(res[that.data.temIds[1]]=='accept'){
                  arr.push('2')
                }
                // else if(res[that.data.temIds[2]]=='accept'){
                  // arr.push('3')
                // }else if(res[that.data.temIds[3]]=='accept'){  //允许
                  // arr.push('4')
                // }
                if(arr.length>0){
                  shareData.other_type = arr.join(',')
                  that.sendSetYue(shareData)
                }
            },
            fail(error){
              console.log(error,'123失败');
            }
          })
      },
      sendSetYue(data){
        wx.$api.sendTemplate(data).then(res=>{
                if(res.code>0){
                }else{
                    wx.showToast({
                      title: res.msg,
                      icon:'none'
                    })
                }
        })
    },

    handleClick () {
        this.setData({
            show: true
        })
    },
    handleClickAdd () {
        this.setData({
            addCartShow: true
        })
    },
    onClose () {
        this.setData({ show: false })
    },
    onCloseAdd () {
        this.setData({ addCartShow: false })
    },
    async toAdd () {
        var that = this
        if (!that.data.userMessage || !that.data.userMessage.id) {
            wx.navigateTo({
                url: '/pages/register/register',
            })
        }else if(that.data.goodNum<1||that.data.goodInfo.goods_can_sell_number<1){
            wx.showToast({
              title: '暂无库存',
              icon:'error'
            })
        } else {
            wx.showLoading({ mask: true })
            let arr = []
            let postData = {
                goods_id: that.data.goodId,
                number: that.data.goodNum
            }
            arr.push(postData)
            let reqData = {
                user_id: that.data.userMessage.id,
                goods_info: JSON.stringify(arr),
            }
            let { code, msg } = await mode.cartAdd(reqData)
            await that.onCloseAdd()
            if (code == 1) {
                // let addGoodId = wx.getStorageSync('addGoodId') || []
                // let cartGoodIds = wx.getStorageSync('cartGoodIds') || []
                // if (!cartGoodIds.includes(that.data.goodId - 0)) { addGoodId.push(that.data.goodId - 0) }
                // wx.setStorage({ key: 'addGoodId', data: addGoodId })
                wx.hideLoading()
                wx.showToast({
                    title: '商品添加成功！',
                    icon: 'none',
                    duration: 2000
                })
            } else {
                wx.hideLoading()
                wx.showToast({
                    title: msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        }

    },
    toBuy () {
        var that = this
        if (!that.data.userMessage || !that.data.userMessage.id) {
            wx.navigateTo({
                url: '/pages/register/register',
            })
        }else if(that.data.goodNum<1||that.data.goodInfo.goods_can_sell_number<1){
            wx.showToast({
              title: '暂无库存',
              icon:'error'
            })
        }  else {
            if (that.data.goodNum > that.data.goodInfo.goods_can_sell_number) {
                wx.showToast({
                    title: '购买数量已超出库存量',
                    icon: 'none',
                    duration: 2000
                })
            } else {
                let arr = []
                let postData = {
                    goods_id: that.data.goodId,
                    number: that.data.goodNum
                }
                arr.push(postData)
                wx.navigateTo({
                    url: '/pages/settlement/settlement?goods_info=' + JSON.stringify(arr)+'&isAbroad='+that.data.goodInfo.is_abroad
                })
            }
        }

    }

})